package com.raspberryCar.service;

import com.raspberryCar.model.Car;
import com.raspberryCar.model.SensorCheck;

import net.java.games.input.Component;
import net.java.games.input.Controller;
import net.java.games.input.ControllerEnvironment;

public class JoystickService {
	public static void main(String[] args) throws InterruptedException {
		Car car = Car.getInstance();
		Controller[] controllers = ControllerEnvironment
				.getDefaultEnvironment().getControllers();
		Controller controller = null;
		for (int i = 0; i < controllers.length; i++) {
			if (controllers[i].getType() == Controller.Type.STICK
					|| controllers[i].getType() == Controller.Type.GAMEPAD) {
				controller = controllers[i];
				System.out.println(controller.getName() + " "
						+ controller.getType());
			}
		}
		if (controller == null) {
			System.out.println("No controller");
			return;
		}
//		SensorCheck check = new SensorCheck(car.getGpioController(),car);
//		new Thread(check).start();
		System.out.println("start");
		while (true) {
			controller.poll();
			Component[] components = controller.getComponents();
			for (int i = 0; i < components.length; i++) {
				if (components[i].isAnalog()) {
					if (components[i].getIdentifier().getName().equals("x")) {
						if (components[i].getPollData() == -1) {
							car.left();
							Thread.sleep(200);
							System.out.println("left");
						} else if (components[i].getPollData() == 1) {
							car.right();
							Thread.sleep(200);
							System.out.println("right");
						}
					} else if (components[i].getIdentifier().getName()
							.equals("y")) {
						if (components[i].getPollData() == -1) {
							car.faw();
							Thread.sleep(200);
							System.out.println("faw");
						} else if (components[i].getPollData() == 1) {

							car.ret();
							Thread.sleep(200);
							System.out.println("ret");
						}
					}
				} else {
					if ((components[i].getIdentifier().getName()
							.equals("Thumb 2") || components[i].getIdentifier()
							.getName().equals("Base 5"))
							&& components[i].getPollData() == 1.0f) {
						// car.fast();
						car.stop();
						Thread.sleep(200);
						System.out.println("stop");
					} else if (components[i].getIdentifier().getName()
							.equals("Top")
							&& components[i].getPollData() == 1.0f) {
						// car.slow();
						Thread.sleep(200);
						System.out.println("slow");
					} else {
						// buffer.append("Off");
					}
				}
			}
			Thread.sleep(20);
		}
	}

}
